package org.grottarossa.tms.PSAPV.ui.home;

import java.util.Hashtable;
import java.util.ResourceBundle;

import org.grottarossa.template.data.pojo.query.Query;
import org.grottarossa.template.drivers.components.tokens.CaseManagementId;
import org.grottarossa.ui.core.ApplicationSession;
import org.grottarossa.ui.core.base.BasePanelView;
import org.grottarossa.ui.core.components.tables.TMSFilteredTable;

import com.vaadin.event.ItemClickEvent;
import com.vaadin.event.ItemClickEvent.ItemClickListener;
import com.vaadin.terminal.Sizeable;
import com.vaadin.ui.Accordion;
import com.vaadin.ui.Component;
import com.vaadin.ui.TabSheet.Tab;
import com.vaadin.ui.VerticalLayout;


/***
 * Rappresenta la HomePage della console PSA
 * @author 
 *
 */
public class HomePage extends BasePanelView<HomePagePresenter>
implements ItemClickListener
{
	Hashtable<Component, String> m_componentForQuery;
	Hashtable<String, Tab> m_tabForQuery;
	VerticalLayout m_layout;
	Accordion m_collapsable;

	public HomePage(ApplicationSession appSession, ResourceBundle localizer)
	{
		super(appSession, localizer);
		initializeComponents();
	}

	@Override
	protected void initializeComponents()
	{
		m_componentForQuery = new Hashtable<Component, String>();
		m_tabForQuery = new Hashtable<String, Tab>();
		m_layout = new VerticalLayout();
		m_layout.setWidth(100, Sizeable.UNITS_PERCENTAGE);
		m_layout.setHeight(100, Sizeable.UNITS_PERCENTAGE);
		setLayout(m_layout);

		m_collapsable = new Accordion();
		m_collapsable.setWidth(100, Sizeable.UNITS_PERCENTAGE);
		m_collapsable.setHeight(100, Sizeable.UNITS_PERCENTAGE);
		m_layout.addComponent(m_collapsable);

	}

	/***
	 * Aggiunge una tabella che  mostra i risultati di una query
	 * @param queryResult I dati risultanti da una query
	 * @param query
	 */
	public void addQuery(Query queryResult, String query)
	{
		TMSFilteredTable queryTable = new TMSFilteredTable(m_appSession, queryResult);
		m_componentForQuery.put(queryTable, query);
		Tab t = m_collapsable.addTab(queryTable, query, null);
		m_tabForQuery.put(query, t);
		queryTable.addListener(this);
	}

	/***
	 * Gestisce il click sugli elementi delle tabelle
	 */
	public void itemClick(ItemClickEvent event)
	{
		String query = m_componentForQuery.get(event.getComponent());
		CaseManagementId caseId = (CaseManagementId)event.getItem().getItemProperty(Query.CaseManagementIdFieldName);
		m_presenter.onItemClicked(caseId, query);
	}

	/***
	 *
	 * Aggiorna la caption della tabella relativa alle righe visitate in una query
	 * @param query
	 * @param visited
	 * @param total
	 */
	public void refreshVisitedRowsCaption(String query, int visited, int total)
	{
		Tab t = m_tabForQuery.get(query);
		t.setCaption(query + " - viste " + visited + " su " + total);
	}
}
